// import { Button, Modal } from 'antd'
import CryptoJS from 'crypto-js'
import Cookies from 'js-cookie'
import { lazy, useContext, useEffect, useRef, useState } from 'react'
import { showMessage } from './components/antd-comp/message'
import { locationContext } from './contexts/locationContext'
import { userContext } from './contexts/userContext'
import { getAppConfig } from './controllers/API'
import { getUserInfo } from './controllers/API/user'

const SECRET_KEY = 'cloud-migu-cooperation' // 请确保这个密钥安全且保密

// App页面懒加载
const App = lazy(() => import('./App'))

/**
 * 登录逻辑修改，使用咪咕跳转带入的authorCode进行登录认证
 * login_mode === 0               根据localStorage的fe-login-mode判断
 * login_mode === 1               进入本地登录
 * login_mode === 2               获取咪咕token并进行验证
 *
 * Sbm          咪咕缩写
 */
export default function AuthPage() {
  const [loading, setLoading] = useState(true)
  const [needAuth, setNeedAuth] = useState(false)
  const [errMsg, setErrMsg] = useState('认证失败，')

  const envInfo = useRef({
    mode: 1,
    baiyingUrl: 'https://smbpaasadmin.migu.com',
    baiyingApiUrl: 'https://paastest.baiying.com.cn', // 咪咕企管后台接口地址
    backUrl: localStorage.getItem('migu-back-url') || 'https://smbpaasadmin.migu.com'
  })

  const { setAppConfig } = useContext(locationContext)
  const { setUserInfo } = useContext(userContext)

  const waitTime = useRef(0)

  const handleAuthStatus = (loading = false, needAuth = true) => {
    setLoading(loading)
    setNeedAuth(needAuth)
    if (needAuth) {
      // 未登录状态时直接跳转到登录页面
      window.location.href = envInfo.current.backUrl || 'https://smbpaasadmin.migu.com'
    }
  }

  const checkLoginMode = () => {
    getAppConfig()
      .then((res: any) => {
        console.log(`=====登录模式：【${res.login_mode}】=====`)
        const resEnv = {
          mode: res.login_mode || 2,
          isDev: res.env === 'dev',
          libAccepts: res.uns_support,
          officeUrl: res.office_url,
          dialogTips: res.dialog_tips,
          dialogQuickSearch: res.dialog_quick_search,
          websocketHost: res.websocket_url || window.location.host,
          baiyingUrl: res.baiying_url || 'https://smbpaasadmin.migu.com', // 咪咕企管后台接口地址
          baiyingApiUrl: res.baiying_api_url || 'https://paastest.baiying.com.cn', // 咪咕企管后台接口地址
          baiyingFilesUrl: res.baiying_files_url || 'https://test-shop-pub-gateway.baiying.com.cn' // 咪咕云空间接口地址
        }
        if (res.login_mode === 0) {
          const feMode = localStorage.getItem('fe-login-mode')
          resEnv.mode = feMode ? parseInt(feMode) : 2
        }
        // resEnv.mode = 1
        setAppConfig(resEnv)
        envInfo.current = {
          mode: resEnv.mode,
          baiyingUrl: resEnv.baiyingUrl,
          baiyingApiUrl: resEnv.baiyingApiUrl,
          backUrl: resEnv.baiyingUrl
        }
        localStorage.setItem('fe-login-mode', resEnv.mode)
        judgeLoginStatus(resEnv.mode)
      })
      .catch(error => {
        console.error(error)
        showMessage({
          content: '登录模式加载错误，请检查网络环境',
          type: 'error'
        })
      })
  }

  const judgeLoginStatus = mode => {
    const queryParams = new URLSearchParams(window.location.search)
    const feLoginMode = queryParams.get('feLoginMode')
    if (feLoginMode) {
      mode = parseInt(feLoginMode) || 1
      localStorage.setItem('fe-login-mode', feLoginMode)
    }

    // 判断跳转链接中是否带cookie参数，有cookie参数时赋值到cookie中

    const miguParam = new URLSearchParams(window.location.search)
    const encryptedData = miguParam.get('data')
    if (encryptedData) {
      // 解密数据
      const bytes = CryptoJS.AES.decrypt(encryptedData, SECRET_KEY)
      const decrypted = bytes.toString(CryptoJS.enc.Utf8)

      // 将字符串转换回对象
      const parsedData = JSON.parse(decrypted)
      if (parsedData && parsedData.access_token_cookie) {
        Cookies.set('access_token_cookie', parsedData.access_token_cookie)
      }

      // 从URL中移除查询字符串，并保留hash部分
      const currentUrl = window.location.href
      const newUrl = currentUrl.split('?')[0]
      window.history.pushState({}, document.title, newUrl)
    }

    // 咪咕特殊处理
    if (mode === 1) {
      setLocalUserInfo()
    } else {
      localStorage.setItem('migu-back-url', envInfo.current.backUrl)
      setLocalUserInfo()
    }
    // if (mode === 1) {
    //   setLocalUserInfo()
    //   return
    // }

    // if (mode === 2) {
    //   const queryParams = new URLSearchParams(window.location.search)
    //   const authorCode = queryParams.get('authorCode')
    //   const backUrl = queryParams.get('fromRoute')
    //   console.log('咪咕参数：', window.location.href, authorCode, backUrl)
    //   if (backUrl) {
    //     const fullUrl = window.location.hash ? backUrl + window.location.hash : backUrl
    //     envInfo.current.backUrl = fullUrl
    //     localStorage.setItem('migu-back-url', fullUrl)
    //   }
    //   if (authorCode) {
    //     getUserTokenByAuthorCode(authorCode)
    //   } else {
    //     verifyMiGuLoginStatus(false)
    //   }
    // }
  }

  const setLocalUserInfo = () => {
    getUserInfo()
      .then((res: any) => {
        const userInfo = {
          ...res
          // enterprise_id: 0
        }
        setUserInfo(userInfo).then(() => {
          handleAuthStatus(false, false)
        })
      })
      .catch(() => {
        // 获取用户失败会直接跳转到login
        handleAuthStatus(false, false)
      })
  }

  const getUserTokenByAuthorCode = authorCode => {
    // 从URL中移除查询字符串，并保留hash部分
    const currentUrl = window.location.href
    const newUrl = currentUrl.split('?')[0]
    window.history.pushState({}, document.title, newUrl)
    // 走咪咕接口，不统一使用axios，因为错误需要单独处理
    fetch(`${envInfo.current.baiyingApiUrl}/login-server/getUserTokenByAuthorCode?authorCode=${authorCode}`)
      .then(response => {
        console.log('getUserTokenByAuthorCode response', response)
        if (response.ok) {
          return response.json()
        } else {
          setErrMsg('Code无效，')
        }
      })
      .then(data => {
        console.log('getUserTokenByAuthorCode data', data)
        if (data.success) {
          localStorage.setItem('migu-token', data.data)
          // token认证获取用户信息
          verifyToken(data.data, true)
        } else {
          setErrMsg(data.message + '，')
          handleAuthStatus(false, true)
        }
      })
      .catch(err => {
        console.error('authorCode error', err)
        handleAuthStatus(false, true)
      })
  }

  const verifyMiGuLoginStatus = (is_redirection = true) => {
    // 测试 token认证
    const token = localStorage.getItem('migu-token')
    if (token) {
      verifyToken(token, is_redirection)
    } else {
      handleAuthStatus(false, true)
    }
  }
  // token验证成功后端直接返回用户信息
  const verifyToken = (token, is_redirection = true) => {
    // 走咪咕接口，不统一使用axios，因为错误需要单独处理
    fetch(`/api/migu/getLoginInfo?is_redirection=${is_redirection}`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        token
      },
      body: JSON.stringify({
        is_redirection
      })
    })
      .then(response => {
        if (response.ok) {
          return response.json()
        } else {
          setErrMsg('登录状态已过期，')
        }
      })
      .then(res => {
        if (!res.data.user_id) {
          setErrMsg('用户ID为空，')
          return
        }
        // getLoginInfo 新加参数  默认为true 页面中刷新的话传递为 false
        // localStorage.setItem('is_redirection', 'successs')
        // ws_token用来给WebSocket连接时使用
        localStorage.setItem('ws_token', res.data.access_token)
        setUserInfo(res.data).then(() => {
          handleAuthStatus(false, false)
        })
      })
      .catch(err => {
        // localStorage.setItem('is_redirection', 'error')
        console.error('verifyToken error', err)
        handleAuthStatus(false, true)
      })
  }

  useEffect(() => {
    checkLoginMode()
  }, [])

  // 每次切换菜单做一次token有效验证
  useEffect(() => {}, [])
  return (
    <>
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      {/* {needAuth && (
        <Modal
          title="认证失败"
          classNames={{
            mask: 'preload-error-mask'
          }}
          closable={false}
          open={true}
          footer={
            <Button
              type="primary"
              onClick={() => (window.location.href = envInfo.current.backUrl || 'https://smbpaasadmin.migu.com')}
            >
              确认
            </Button>
          }
        >
          <p>{errMsg}请点击确认重新授权登录</p>
        </Modal>
      )} */}
      {!loading && !needAuth && <App />}
    </>
  )
}
